package com.huzz.config;

import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @Name 名称
 * @Description 描述
 * @Author 童年的纸飞机
 * @Since 2023-08-2023/8/2 09:26
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    /**
     * 注册 Sa-Token 全局过滤器
     * @return
     */
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                 .addInclude("/**")
                .setAuth(obj -> {
                    // 校验 Same-Token 身份凭证
                    SaSameUtil.checkCurrentRequestToken();
                })
                .setExcludeList(excludePathPatterns)
                .setError(e -> SaResult.error(e.getMessage()));
    }

    private static List<String> excludePathPatterns = Arrays.asList(
            "/doc.html/**",
            "/swagger-ui.html/**",
            "/swagger-resources/**",
            "/webjars/**",
            "/v2/**",
            "/error",
            "/favicon.ico",
            "/csrf"
    );

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
    }
}
